package cn.com.anypay.manager.common.validation;

import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;
import java.util.regex.Pattern;

/**
 * 邮箱格式验证器实现
 */
public class EmailFormatValidator implements ConstraintValidator<EmailFormat, String> {

    private boolean allowEmpty;
    private EmailFormat.EmailType type;
    private boolean allowInternationalDomain;

    // 标准邮箱正则表达式
    private static final String STANDARD_EMAIL_PATTERN = 
        "^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$";
    
    // 严格邮箱正则表达式（RFC 5322标准）
    private static final String STRICT_EMAIL_PATTERN = 
        "^[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?\\.)+ [a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$";
    
    // 简单邮箱正则表达式
    private static final String SIMPLE_EMAIL_PATTERN = 
        "^\\S+@\\S+\\.\\S+$";

    @Override
    public void initialize(EmailFormat constraintAnnotation) {
        this.allowEmpty = constraintAnnotation.allowEmpty();
        this.type = constraintAnnotation.type();
        this.allowInternationalDomain = constraintAnnotation.allowInternationalDomain();
    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
        // 空值检查
        if (value == null || value.trim().isEmpty()) {
            return allowEmpty;
        }

        // 去除首尾空格
        String cleanEmail = value.trim().toLowerCase();

        // 基本长度检查
        if (cleanEmail.length() > 254) { // RFC 5321 限制
            return false;
        }

        // 根据类型选择验证规则
        boolean isValid = switch (type) {
            case STANDARD -> validateStandardEmail(cleanEmail);
            case STRICT -> validateStrictEmail(cleanEmail);
            case SIMPLE -> validateSimpleEmail(cleanEmail);
        };

        // 额外的域名检查
        if (isValid && !allowInternationalDomain) {
            return validateDomainAscii(cleanEmail);
        }

        return isValid;
    }

    /**
     * 验证标准邮箱格式
     */
    private boolean validateStandardEmail(String email) {
        return Pattern.matches(STANDARD_EMAIL_PATTERN, email);
    }

    /**
     * 验证严格邮箱格式
     */
    private boolean validateStrictEmail(String email) {
        return Pattern.matches(STRICT_EMAIL_PATTERN, email);
    }

    /**
     * 验证简单邮箱格式
     */
    private boolean validateSimpleEmail(String email) {
        return Pattern.matches(SIMPLE_EMAIL_PATTERN, email);
    }

    /**
     * 验证域名是否为ASCII字符
     */
    private boolean validateDomainAscii(String email) {
        String domain = email.substring(email.lastIndexOf('@') + 1);
        return domain.matches("^[a-zA-Z0-9.-]+$");
    }
}